package org.mock.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.mock.common.Condition;
import org.mock.entity.TravelHotelAvail;
import org.mock.mapper.TravelHotelAvailMapper;
import org.mock.service.TravelHotelAvailService;
import org.mock.dto.TravelHotelAvailDTO;
import org.mock.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * 服务实现类
 *
 * @author AI
 * @since 2025-07-15
 */
@Service
@AllArgsConstructor
@Slf4j
public class TravelHotelAvailServiceImpl implements TravelHotelAvailService {

    protected TravelHotelAvailMapper travelHotelAvailMapper;

    @Override
    public TravelHotelAvailDTO handleRequest(JSONObject request) {
        log.info("[getHotelAvail-travelPort] 请求：{}", request);
        TravelHotelAvailDTO dto = new TravelHotelAvailDTO();

        JSONObject propertiesQuerySpecificPropertyList = request.getJSONObject("PropertiesQuerySpecificPropertyList");

        if (propertiesQuerySpecificPropertyList.containsKey("RateCandidates")) {
            JSONObject rateCandidates = propertiesQuerySpecificPropertyList.getJSONObject("RateCandidates");
            JSONArray rateCandidate = rateCandidates.getJSONArray("RateCandidate");
            JSONObject rateCandidateItem = rateCandidate.getJSONObject(0);
            String propertyCode = rateCandidateItem.getString("propertyCode");
            log.info("propertyCode: {}", propertyCode);
            dto.setPropertyCode(propertyCode);
        }
        return dto;
    }

    @Override
    public TravelHotelAvailDTO handleQueryWrapper(TravelHotelAvailDTO dto) {
        return dto;
    }

    @Override
    public TravelHotelAvail getOne(TravelHotelAvailDTO dto) {
        List<TravelHotelAvail> list = travelHotelAvailMapper.selectList(Condition.getQueryWrapper(BeanCopyUtils.copy(dto, TravelHotelAvail.class)));
        if (CollUtil.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public String handleData(TravelHotelAvail data, TravelHotelAvailDTO originalQuery) {
        if (ObjectUtil.isEmpty(data)) {
            log.info("暂无数据");
            return StrUtil.EMPTY;
        }

        //修改响应体中的酒店编号，改成传入的那个，这样就总是会有价格了
        String response = data.getResponse();
        try {
            log.info("修改响应体中的酒店编号");
            String propertyCode = originalQuery.getPropertyCode();

            JSONObject responseJson = JSON.parseObject(response);


        } catch (Exception e) {
            log.error("解析返回结构异常", e);
        }
        return response;
    }
}
